package cn.pop.hsp_system_v2.Controller;

import cn.pop.hsp_system_v2.Pojo.OutPatient;
import cn.pop.hsp_system_v2.Pojo.Patient;
import cn.pop.hsp_system_v2.Pojo.SystemUser;
import cn.pop.hsp_system_v2.Pojo.Vo.SystemUserAndPatientVo;
import cn.pop.hsp_system_v2.Service.IPatientService;
import cn.pop.hsp_system_v2.Service.ISystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.List;


@Controller
public class DloginController {
    @Autowired
    private ISystemUserService tsystemUserService;
    @Autowired
    private IPatientService iPatientService;

    @PostMapping("/login")
    public String login(SystemUser systemUser,HttpSession httpSession, Model model){
            if(!systemUser.getUsername().isEmpty()&&!systemUser.getPassword().isEmpty()){
                SystemUser user = tsystemUserService.selectLogin(systemUser);
                System.out.println(user.getId());
                httpSession.setAttribute("userid",user.getId());
                if(user!=null&&user.getIsvalid()!=1){
                    Patient patient_user=iPatientService.selectPatientById(user.getId());
                    if (patient_user==null){
                        return "bindMCard.html";
                    }
                    httpSession.setAttribute("user", patient_user);
                    Collection<OutPatient> outPatients= iPatientService.selectAllOutPatient();
                    System.out.println(outPatients);
                    model.addAttribute("outpatients",outPatients);
                    return "/patient/department";
                }
                model.addAttribute("msg", "登录信息错误或账户已被冻结");
                return "/login";
            }
            model.addAttribute("msg", "非法登录!");
            return "/login";
    }

    @PostMapping("/register")
    public String register(SystemUser systemUser,Model model){

        if(!systemUser.getUsername().isEmpty()&&!systemUser.getPassword().isEmpty()){
            int i = tsystemUserService.insertRegitst(systemUser);
            if(i==200){
                model.addAttribute("msg","注册成功!请登录账户");
                return "/login";
            }else if (i==201){
                model.addAttribute("msg","系統一場，請聯係管理員");
                return "/register";
            }else if (i==202){
                model.addAttribute("msg","注冊失敗");
                return "/register";
            }
        }
        model.addAttribute("msg", "输入信息有误");
        return "/register";
    }
}
